package com.laixu.estore.service;

import com.laixu.estore.bean.pojo.Book;
import com.laixu.estore.bean.vo.BookVo;
import com.laixu.estore.dao.BookDao;
import com.laixu.estore.util.BeanCopyUtils;
import com.laixu.estore.web.exception.BookStoreException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Auther: vanse(lc)
 * @Date: 2025/3/14-03-14-11:01
 * @Description：业务层 IBookService 接口
 * // impl/BookServiceImpl
 */
@Service
@RequiredArgsConstructor
public class BookService {
    private final BookDao bookDao;

    // springel
    @Value("${myIp}")
    private String myIp;

    public void insert(Book book) {
        // 1.校验书籍
        String name = book.getName();
        if (!StringUtils.hasText(name)) {
//               throw new RuntimeException("书籍名字不能为空");
//                throw new BookStoreException(20000,"书籍名字不能为空");
            throw new BookStoreException(BookStoreException.CodeMsgEnum.BOOK_NAME_IS_NULL);
        }
        // 2.调用dao层入库
        bookDao.insert(book);
    }

    public List<BookVo> showBooks() {
        // 数据库返回对应的实体
        List<Book> bookList = bookDao.showBooks();
//        System.out.println("bookList = " + bookList);
        // List<Book> -> List<BookVo>
        List<BookVo> bookVos = BeanCopyUtils.copyBeanList(bookList, BookVo.class);
        // 书籍图片需要额外处理 加上服务器的前缀
        // http://localhost:7777/  bookcover/%E6%B2%89%E6%80%9D%E5%BD%95.jpg
        for (BookVo bookVo : bookVos) {
            bookVo.setCover(myIp + bookVo.getCover());
        }
        return bookVos;
    }

    public BookVo getBookById(Integer id) {
        Book book =  bookDao.getBookById(id);
        BookVo bookVo = BeanCopyUtils.copyBean(book, BookVo.class);
        bookVo.setCover(myIp + bookVo.getCover());
        return bookVo;
    }
}